package com.opennews.openplatform.myspringbootmvccore.extension

import jakarta.servlet.http.HttpServletRequest
import java.net.InetAddress
import java.net.UnknownHostException

/**
 * Gets client request ip address
 */
fun HttpServletRequest.getRequestIpAddress(): String {
    val localhostIpv4 = "127.0.0.1"
    val localhostIpv6 = "0:0:0:0:0:0:0:1"
    val unknownStatus = "unknown"

    var ipAddress = this.getHeader("X-Forwarded-For")

    if (ipAddress.isNullOrBlank() || unknownStatus.equals(ipAddress, ignoreCase = true)) {
        ipAddress = this.getHeader("Proxy-Client-IP")
    }

    if (ipAddress.isNullOrBlank() || unknownStatus.equals(ipAddress, ignoreCase = true)) {
        ipAddress = this.getHeader("WL-Proxy-Client-IP")
    }

    if (ipAddress.isNullOrBlank() || unknownStatus.equals(ipAddress, ignoreCase = true)) {
        ipAddress = this.remoteAddr

        if (localhostIpv4 == ipAddress || localhostIpv6 == ipAddress) {
            try {
                val inetAddress = InetAddress.getLocalHost()
                ipAddress = inetAddress.hostAddress
            } catch (e: UnknownHostException) {
                e.printStackTrace()
            }
        }
    }

    if (!ipAddress.isNullOrBlank() && ipAddress.length > 15 && ipAddress.contains(",")) {
        ipAddress = ipAddress.substring(0, ipAddress.indexOf(","))
    }

    return ipAddress
}